﻿#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QFileDialog>
#include <QFile>
#include <QTextStream>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    colCount=7;
    model=new QStandardItemModel(2,colCount);
    selectionModel=new QItemSelectionModel(model);

    ui->tableView->setModel(model);
    ui->tableView->setSelectionModel(selectionModel);
    auto headView=ui->tableView->horizontalHeader();
    headView->setSectionResizeMode(QHeaderView::Stretch);

    ui->tableView->setSelectionMode(QAbstractItemView::ExtendedSelection);
    ui->tableView->setSelectionBehavior(QAbstractItemView::SelectItems);

    connect(selectionModel,SIGNAL(currentChanged(const QModelIndex &, const QModelIndex &)),
                this,SLOT(on_currentChanged(const QModelIndex &, const QModelIndex &)));

    ui->tableView->setItemDelegateForColumn(4,&salayDelegate);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::initModel(const QStringList &list)
{
    QString headLine =list[0];
    QStringList haedList=headLine.split(QRegExp("\\s+"),QString::SkipEmptyParts);
    model->setHorizontalHeaderLabels(haedList);

    int rows=list.count();
    for(int i=1;i<rows;i++)
    {
        QString line=list[i];
        QStringList list=line.split(QRegExp("\\s+"),QString::SkipEmptyParts);
        for(int j=0;j<list.size()-1;j++)
        {
            QStandardItem*item=new QStandardItem(list[j]);
            model->setItem(i-1,j,item);
        }

        QStandardItem*item=new QStandardItem(haedList[colCount-1]);
        item->setCheckable(true);
        if(list[colCount-1]=="否")
        {
            item->setCheckState(Qt::Unchecked);
        }
        else
        {
            item->setCheckState(Qt::Checked);
        }
        model->setItem(i-1,colCount-1,item);
    }



}


void MainWindow::on_action_open_triggered()
{
    QString fileName=QFileDialog::getOpenFileName(this,"打开一个文件",QCoreApplication::applicationDirPath(),"文本文件(*.txt);;所有文件(*.*)");
    if(fileName.isEmpty())return;
    QFile file(fileName);
    QTextStream stream(&file);
    if(!file.open(QIODevice::ReadOnly|QIODevice::Text))
    {
        return ;
    }
    QStringList contents;
    while(!stream.atEnd())
    {
        QString line=stream.readLine();
        contents.push_back(line);
        ui->plainTextEdit->appendPlainText(line);
    }
    initModel(contents);
    file.close();
}

void MainWindow::on_action_add_triggered()
{
    selectionModel->clearSelection();
    QStringList list={"姚国林","男","2003-12-28","BOSS","100000","1.0","婚否"};
    QList<QStandardItem*>itemList;
    for(int i=0;i<list.count();i++)
    {
        QStandardItem *item=new QStandardItem(list[i]);
        itemList.push_back(item);
    }
    itemList[colCount-1]->setCheckable(true);
    model->insertRow(model->rowCount(),itemList);
    QModelIndex index=model->index(model->rowCount()-1,0);
    selectionModel->setCurrentIndex(index,QItemSelectionModel::Select);
}

void MainWindow::on_action_insert_triggered()
{
    selectionModel->clearSelection();
    QStringList list={"姚国林","男","2003-12-28","BOSS","100000","1.0","婚否"};
    QList<QStandardItem*>itemList;
    for(int i=0;i<list.count();i++)
    {
        QStandardItem *item=new QStandardItem(list[i]);
        itemList.push_back(item);
    }
    itemList[colCount-1]->setCheckable(true);
    QModelIndex index=selectionModel->currentIndex();
    model->insertRow(index.row(),itemList);
    selectionModel->setCurrentIndex(index,QItemSelectionModel::Select);
}

void MainWindow::on_action_del_triggered()
{
    QModelIndex index=selectionModel->currentIndex();
    if(index.row()==model->rowCount()-1)
    {
        model->removeRow(index.row());
    }
    else
    {
        model->removeRow(index.row());
        selectionModel->setCurrentIndex(index,QItemSelectionModel::Select);
    }
}

void MainWindow::on_action_see_triggered()
{
    ui->plainTextEdit->clear();
    QString str;
    for(int i=0;i<colCount;i++)
    {
        auto item=model->horizontalHeaderItem(i);
        str+=item->text()+"\t\t";
    }
    ui->plainTextEdit->appendPlainText(str);

    for(int i=0;i<model->rowCount();i++)
        {
            str="";//每一行都从空字符串相加
            for(int j=0;j<colCount-1;j++)//最一列单独处理
            {
                auto item=model->item(i,j);
                str+=item->text()+"\t\t";
            }

            auto item=model->item(i,colCount-1);//最后一列
            if(item->checkState()==Qt::Checked)//根据是否勾选来选择
            {
                str+="是";
            }
            else
            {
                str+="否";
            }
            ui->plainTextEdit->appendPlainText(str);//会自动换行

        }



}

void MainWindow::on_action_save_triggered()
{
    //获取保存文件名
        QString fileName=QFileDialog::getSaveFileName(this,"保存文件",QCoreApplication::applicationDirPath());
        if(fileName.isEmpty())//如果文件名为空，就直接返回
            {
                return;
            }
        QFile qFile(fileName);
        if(!qFile.open(QIODevice::ReadWrite|QIODevice::Text|QIODevice::Truncate))//通过打不开文件直接返回
           {
               return;
           }
        QTextStream stream(&qFile);
        QString str;
            for(int i=0;i<colCount;i++)
            {
                auto item=model->horizontalHeaderItem(i);//拿到表头的每项数据
                str+=item->text()+"\t\t";//将每项的内容加到字符串中
            }
            stream<<str<<"\n";//写入文件中

            for(int i=0;i<model->rowCount();i++)
            {
                str="";//每一行都从空字符串相加
                for(int j=0;j<colCount-1;j++)//最一列单独处理
                {
                    auto item=model->item(i,j);
                    str+=item->text()+"\t\t";
                }

                auto item=model->item(i,colCount-1);
                if(item->checkState()==Qt::Checked)
                {
                    str+="是";
                }
                else
                {
                    str+="否";
                }
                stream<<str<<"\n";//写入文件中
            }
}



void MainWindow::on_action_right_triggered()
{
    if(!selectionModel->hasSelection())//没有选择就直接退出
    {
        return;
    }
    auto indexs=selectionModel->selectedIndexes();//通过选择模型可以获取选择的多个单元格的模型索引
    for(int i=0;i<indexs.count();i++)
    {
        QStandardItem * item=model->itemFromIndex(indexs[i]);//通过模型索引获取项
        item->setTextAlignment(Qt::AlignVCenter|Qt::AlignRight);//设置文本对其方式为右对其，垂直居中
    }
}


void MainWindow::on_action_center_triggered()
{
   if(!selectionModel->hasSelection())//没有选择就直接退出
   {
       return;
   }
   auto indexs=selectionModel->selectedIndexes();//通过选择模型可以获取选择的多个单元格的模型索引
   for(int i=0;i<indexs.count();i++)
   {
       QStandardItem * item=model->itemFromIndex(indexs[i]);//通过模型索引获取项
       item->setTextAlignment(Qt::AlignVCenter|Qt::AlignHCenter);//只是这里参数不一样
   }
}




    void MainWindow::on_action_left_triggered()
    {
        if(!selectionModel->hasSelection())//没有选择就直接退出
        {
            return;
        }
        auto indexs=selectionModel->selectedIndexes();//通过选择模型可以获取选择的多个单元格的模型索引
        for(int i=0;i<indexs.count();i++)
        {
            QStandardItem * item=model->itemFromIndex(indexs[i]);//通过模型索引获取项
            item->setTextAlignment(Qt::AlignVCenter|Qt::AlignLeft);
        }
    }



    void MainWindow::on_action_bold_triggered(bool checked)
    {
        if(!selectionModel->hasSelection())//没有选择就直接退出
        {
            return;
        }

        auto indexs=selectionModel->selectedIndexes();//通过选择模型可以获取选择的多个单元格的模型索引

        for(int i=0;i<indexs.count();i++)
        {
            QStandardItem * item=model->itemFromIndex(indexs[i]);//通过模型索引获取项
            QFont font=item->font();
            font.setBold(true);
            item->setFont(font);
        }
    }

    void MainWindow::on_currentChanged(const QModelIndex &current, const QModelIndex &previous)
    {
        if(current.isValid())//如果当前点击的单元格是有效的。
        {
            auto item=model->itemFromIndex(current);//通过当前模型索引获取单元格
            ui->action_bold->setChecked(item->font().bold());//如果是粗体就打开，不是就关闭
        }
    }

